<template>
  <div class="content-wrap content-container" v-loading="loading">
    <!-- 搜索区域 -->
    <el-form class="search-wrap" v-model="searchFormData">
      <el-form-item
        class="search-wrap-item"
        label="标题关键字："
        prop="projectTitle"
      >
        <el-input
          width="160px"
          placeholder="请输入标题关键字"
          v-model="searchFormData.projectTitle"
          clearable
          @input="getAllNoTipRequirement"
        ></el-input>
      </el-form-item>
      <el-form-item class="search-wrap-item" label="时间：" prop="time">
        <el-date-picker
          style="width: 240px"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :value-on-clear="null"
          v-model="searchFormData.time"
          @change="getAllNoTipRequirement"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="createRequirementClick"
          >创建需求</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 待审核详细设计列表 -->
    <div class="card-wrap-table">
      <el-table :data="allNoTipRequirement" border style="width: 100%; height: 100%;font-size: 12px;">
        <el-table-column
          fixed
          type="index"
          label="序号"
          width="60"
          align="center"
        ></el-table-column>
        <el-table-column label="需求名称" prop="itemRequirementName" min-width="460">
          <template #="{ row }">
            <p class="table-requirement-name" @click="handleRowClick(row.itemRequirementId)">{{ row.itemRequirementName }}</p>
          </template>
        </el-table-column>
        <el-table-column label="提测人" prop="userName" width="80" align="center">
          <template #="{ row }">
            <span>{{ row.userName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="提测时间" prop="guessTime3" width="100" align="center">
            <template #="{ row }">
                <span>{{ tableTimeDate(row.guessTime3) }}</span>
            </template>
        </el-table-column>
        <el-table-column label="研发任务" prop="processJob" width="200" align="center">
          <template #="{ row }">
            <span>{{ row.processJob }}</span>
          </template>
        </el-table-column>
        <el-table-column label="参与测试" prop="testUserNames" width="160" align="center">
            <template #="{ row }">
                <span>{{ row.testUserNames }}</span>
            </template>
        </el-table-column>
        <el-table-column class="table-download" label="附件" prop="itemRequirementWorldDetailed" width="160" align="center">
            <template #="{ row }">
                <span @click="handleDownloadFile(handleFileName(row.itemRequirementWorldDetailed), baseUrl)">{{ handleFileName(row.itemRequirementWorldDetailed).name }}</span>
            </template>
        </el-table-column>
        <el-table-column 
            label="审核状态" 
            prop="itemRequirementIsEnter" 
            width="80" 
            align="center">
          <template #="{ row }">
            <span
              :style="{
                color: enterStatus(row.itemRequirementIsEnter).bgColor,
              }"
              >{{ enterStatus(row.itemRequirementIsEnter).content }}</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button
              size="small"
              type="primary"
              :disabled="row.itemRequirementIsEnter == 2"
              @click="handleOpenDialog(row)"
            >
              审核
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 审核需求弹窗 -->
    <el-dialog v-model="dialogNoTipVisible" title="审核需求" width="1200" style="margin-top: 20px;"  :close-on-click-modal="false" @close="handleColseDialog" @closed="handleColseDialog">
      <el-form
        label-position="right"
        label-width="160px"
        ref="showNoTipFormRef"
        :rules="showNoTipRules"
        :model="showTipJTOYForm">
        <el-form-item label-width="0">
          <CommonRequirementInfoVue v-if="dialogNoTipVisible" :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
        </el-form-item>
        <!-- <el-form-item label="会议纪要：" prop="itemRequirementMeetingEasy">
          <el-input
            maxlength="200"
            placeholder="请输入提测评审会议纪要..."
            show-word-limit
            type="textarea"
            v-model="showTipJTOYForm.itemRequirementMeetingEasy"
          />
        </el-form-item> -->
        <el-form-item label="对详细设计的评价：" prop="itemRequirementGTOYTip">
          <el-input
            maxlength="200"
            placeholder="请输入对详细设计的评价"
            show-word-limit
            type="textarea"
            v-model="showTipJTOYForm.itemRequirementGTOYTip"
          />
        </el-form-item>
        <el-form-item label="对详细设计的评分：" prop="itemRequirementGTOYTipNumber">
          <el-input-number
            style="width: 100px;"
            class="mx-4"
            min="0"
            max="500"
            controls-position="right"
            v-model="showTipJTOYForm.itemRequirementGTOYTipNumber"
          />
        </el-form-item>
        <el-form-item>
          <!-- <template #footer> -->
            <div class="dialog-footer" style="width: 100%; display: flex;justify-content: right;">
              <el-button @click="handleColseDialog">取消</el-button>
              <el-button type="primary" @click="submitReview(showNoTipFormRef)"> 通过 </el-button>
            </div>
          <!-- </template> -->
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 需求详情弹窗 -->
    <el-dialog style="width: 1200px;"  :close-on-click-modal="false" v-model="dialogInfoVisible" @close="dialogInfoVisible = false"  @closed="dialogInfoVisible = false">
        <CommonRequirementInfoVue v-if="dialogInfoVisible" :isRequirementID="isRequirementID" :clearData="clearData"></CommonRequirementInfoVue>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification, FormInstance, } from "element-plus";
import { ElForm } from "element-plus";
import {
  GetMyRequirementNoTip,
  PutShowTipJTOY,
} from "@/api/newDemands/index";
import { tableTimeDate, enterStatus, handleDownloadFile, handleFileName, isValidateString } from "@/utils/utils";
import useCommonDataStore from "@/store/common/common";
import CommonRequirementInfoVue from "../comomRequirementInfo.vue";

let router = useRouter();
let useCommonStore = useCommonDataStore();
const loading = ref(false);
const userAuthId = ref<any>(null); //当前用户权限id
const searchFormData = ref({
  projectTitle: "",
  time: [null, null],
});

const dialogNoTipVisible = ref(false); //审核需求弹窗

const isRequirementID = ref<any>(null); //当前操作需求ID
const isRequirementData = ref<any>(null); //当前操作任务数据
const baseUrl = ref(import.meta.env.VITE_SERVE);//服务器地址

const allNoTipRequirement = ref<any>([]); //所有待审核的详细设计
const dialogInfoVisible = ref(false);//查看需求弹窗控件
const clearData = ref(false);//控制是否清空子组件数据

const showNoTipFormRef = ref<FormInstance>();//定义审核表单实例

// 审核表单校验规则
const showNoTipRules = reactive({
 /*  itemRequirementMeetingEasy: [
    {
      required: true,
      message: "必填",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      }
    }
  ], */
  itemRequirementGTOYTip: [
    {
      required: true,
      message: "必填",
      trigger: "blur",
      validator: (rule: any, value: any, callback: any) => {
        if (isValidateString(value)) {
          callback(new Error("必填，且不能为空格或空行！"));
        } else {
          callback();
        }
      }
    }
  ],
  itemRequirementGTOYTipNumber: [{ required: true, message: "必填", trigger: "blur" }],
});

/* 提交审核表单数据 */
const showTipJTOYForm = ref<any>({
  requirementChildId: null,
  itemRequirementMeetingEasy: "",
  itemRequirementGTOYTip: "",
  itemRequirementGTOYTipNumber: 100,
  worldDetailedIsNext: 3
});


// TODO 点击创建任务
const createRequirementClick = () => {
  router.push({
    path: "/requirement/create",
  });
};

//  获取【我待审核的详细设计】数据
const getAllNoTipRequirement = async () => {
  loading.value = true;

  const { data } = await GetMyRequirementNoTip({
    projectTitle: searchFormData.value.projectTitle,
    beginTime:
      searchFormData.value.time === null ? null : searchFormData.value.time[0],
    endTime:
      searchFormData.value.time === null ? null : searchFormData.value.time[1],
  });

  if (data.code === 200 && data.data !== null) {
    allNoTipRequirement.value = data.data
      .map((item: any) => {
        return {
          ID: item.ID,
          itemRequirementId: item.itemRequirementId,
          itemRequirementName:item.itemRequirementName, 
          userName: item.userName,
          testUserNames: item.testUserNames,
          processJob: item.processJob,
          itemRequirementWorldDetailed: item.itemRequirementWorldDetailed,
          guessTime3: item.guessTime3
        };
      });

    console.log("待审核需求：", allNoTipRequirement.value);
    ElMessage.success(data.msg);
    loading.value = false;
    return;
  } else {
    ElMessage.error(data.msg);
    loading.value = false;
    return;
  }
};

// 查看需求
const handleRowClick = async (id: number) => {
  console.log("查看需求:", id);
  dialogInfoVisible.value = true;
  isRequirementID.value = id;
};



// TODO 开启审核需求弹窗
const handleOpenDialog = (val: any) => {
  console.log("当前审核任务：", val);
  isRequirementID.value = val.itemRequirementId;
  isRequirementData.value = val;
  showTipJTOYForm.value.requirementChildId = val.ID;
  dialogNoTipVisible.value = true;
};

// TODO 初始化当前操作需求数据
const handleInitData = () => {
  isRequirementData.value = null;
  isRequirementID.value = null;
  showTipJTOYForm.value = {
    requirementChildId: null,
    itemRequirementMeetingEasy: "",
    itemRequirementGTOYTip: "",
    itemRequirementGTOYTipNumber: 100,
    worldDetailedIsNext: 3
  }
};



// TODO 提交审核结果
const submitReview = async (formEl:FormInstance | undefined) => {
  if (!formEl) {
    console.error("表单验证失败，请将内容填写完整:");
    return;
  };
  const validatePromise = formEl.validate();
  try {
    await validatePromise;

    // 校验通过
    const { data } = await PutShowTipJTOY(showTipJTOYForm.value);
    if (data.code === 200) {
      ElMessage.success(data.msg);
      clearData.value = true;
      dialogNoTipVisible.value = false;
      handleInitData();

      loading.value = true;
      await getAllNoTipRequirement();
      loading.value = false;
      return;
    } else {
      ElMessage.error(data.msg);
      clearData.value = true;
      dialogNoTipVisible.value = false;
      handleInitData();
      return;
    }

  } catch (error) {
    console.log("表单校验失败，请将内容填写完整", error);
    return;
  };
};

// TODO 取消审核
const handleColseDialog = () => {
  console.log("取消评审")
  handleInitData();
  clearData.value = true;
  dialogNoTipVisible.value = false;
};


onMounted(async () => {
  getAllNoTipRequirement();
});
</script>

<style lang="scss" scoped>
.content-container {
  background-color: white;
  display: flex;
  flex-direction: column;
  padding: 10px;

  // TODO 搜索区域
  .search-wrap {
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    border-bottom: 1px solid #dcdfe6;

    .search-wrap-item {
      margin-right: 20px;
      min-width: 200px;
      font-weight: bold;
      font-size: 24px;
      font-family: Arial, Helvetica, sans-serif;
      color: #000;
    }
  }

    // TODO 数据区域
    .table-requirement-name:hover,
    .table-download:hover {
        color: #409EFF;
        cursor: pointer;
    }

    // TODO 查看审核记录弹窗
    .record-title {
    display: flex;
    flex-direction: row;
    padding: 5px 10px;
    margin-bottom: 10px;
    background-color: #f0f0f0;
    border-radius: 2px;
    p {
      margin-right: 20px;
    }

  }
  // 需求草稿
  .info-file-box {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-direction: row;
    margin: 10px 0 0;
    .info-content-title {
        width: 100px;
        padding: 0 10px;
    }

    .info-file-ul {
        width: calc(100% - 70px);
        text-align: left;
        display: flex;
        flex-direction: row;
        .info-file-item {
            width: 100px;
            margin-right: 10px;
            color: blue;
        }
        .info-file-item:hover {
            color: #409EFF;
            cursor: pointer;
        }
    }
  }
}
</style>
